//
//  LXStatusOriginalView.swift
//  weibo
//
//  Created by lixin on 16/4/22.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

import SnapKit

class LXStatusOriginalView: UIView {

    //记录原创微博的底部约束
    var originalViewBottomConstraint: Constraint?
    
    var status: LXStatus?{
       
        didSet{
            
            headImageView.sd_setImageWithURL(NSURL(string: status?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
        
            nameLabel.text = status?.user?.screen_name
            
            rankImageView.image = getRankImage(status?.user?.rank ?? 0)
            
            timeLable.text = getTimeString(status!.created_at!)
            
            sourceLabel.attributedText = getSourceString(status?.source)
            
            verifiedImageView.image = getVerifiedImage(status?.user?.verified_type ?? -1)//认证
            
//            contentLabel.text = status?.text
            
            contentLabel.attributedText = getWeiboAttr(status?.text ?? "")

            //卸载原创微博底部约束
            self.originalViewBottomConstraint?.uninstall()
            
            if status?.pic_ids?.count != 0{
                
                pictureView.pictureInfo = status?.pic_ids
                
                self.snp_makeConstraints(closure: { (make) -> Void in
                    
                    self.originalViewBottomConstraint = make.bottom.equalTo(pictureView.snp_bottom).offset(10).constraint
                })
                
                pictureView.hidden = false
                
            }else{
                
                self.snp_makeConstraints(closure: { (make) -> Void in
                    
                    self.originalViewBottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(10).constraint
                })
                
                pictureView.hidden = true//隐藏配图（cell复用问题）
            }

        }
    }
    
    func getWeiboAttr(text: String) -> NSMutableAttributedString{
        
        //把微博的正文的字符串转成一个可变的富文本
        let allAttr = NSMutableAttributedString(string: text)
        
        var matchResult: [LXMatchResult] = [LXMatchResult]()
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, result, range, _) -> Void in
           
            let match  = LXMatchResult(string: (result.memory as! String), range: range.memory)
           
            matchResult.append(match)
            
        }
        
        //由于越界问题倒着遍历
        for match in matchResult.reverse(){
            
            let emoticon = LXEmoticonTools.sharedTools.getEmoticonWithChs(match.string)
           
            guard let e = emoticon else{
                
                return NSMutableAttributedString(string: "")
            }
            
            let path = "\(e.path ?? "")\(e.png ?? "")"
            
            let image = UIImage(named: path, inBundle: LXEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            let lineHeight = UIFont.systemFontOfSize(14).lineHeight
           
            let att = NSTextAttachment()
            
            att.image = image
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
          
            let attr = NSAttributedString(attachment: att)
            
            //替换
            allAttr.replaceCharactersInRange(match.range, withAttributedString: attr)
        }
        
        return allAttr
    }
    
    ///MARK: - 时间
    func getTimeString(time: String) -> String{
        
        let dateFormatter = NSDateFormatter()
        
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        
        let weiboDate = dateFormatter.dateFromString(time)!
        
        let isThisYear = weiboTimeIsThisYear(weiboDate)
        
        if isThisYear{
            
            let calendar =  NSCalendar.currentCalendar()
            
            if calendar.isDateInToday(weiboDate){
               
                let s = NSDate().timeIntervalSinceDate(weiboDate)
               
                if s < 60{
                    
                    return "刚刚"
                    
                }else if s >= 60 && s < 3600{
                    
                    return "\(Int(s / 60))分钟前"
                    
                }else{
                   
                    return "\(Int(s / 3600))小时前"
                }
                
            }else if calendar.isDateInYesterday(weiboDate){
                
                dateFormatter.dateFormat = "昨天 HH:mm"
                
                return dateFormatter.stringFromDate(weiboDate)
                
            }else{
                
                dateFormatter.dateFormat = "MM月dd日 HH:mm"
                
                return dateFormatter.stringFromDate(weiboDate)
            }
            
        }else{
            
            dateFormatter.dateFormat = "yyyy年MM月dd日 HH:mm"
            
            return dateFormatter.stringFromDate(weiboDate)
            
        }
    }
    
    //MARK: - 判断是否是今年
    func weiboTimeIsThisYear(weibodate: NSDate) -> Bool{
        
        let dateFormatter = NSDateFormatter()
        
        dateFormatter.dateFormat = "yyyy"
        
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
      
        let weiboStr = dateFormatter.stringFromDate(weibodate)
        
        let currentStr = dateFormatter.stringFromDate(NSDate())
  
        if weiboStr == currentStr{
            
            return true
            
        }else{
            
            return false
        }
        
    }
    
    ///MARK: - 处理来源字符串
    func getSourceString(source: String?) -> NSMutableAttributedString{
        
        guard let s = source where s.containsString("\">") else{
            
            return NSMutableAttributedString(string: "")
        }
        
        let startRange = s.rangeOfString("\">")!
        
        let endRange = s.rangeOfString("</a")!
        
        let result = s.substringWithRange(startRange.endIndex..<endRange.startIndex)
       
        let name = "来自 \(result)"
        
        let attr = NSMutableAttributedString(string: name)//通过富文本
       
        let range = (name as NSString).rangeOfString("来自")
        
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: range)
       
        return attr
        
    }
    
    ///MARK: - 等级图标
    func getRankImage(rank: Int) -> UIImage?{
        if rank > 0 && rank < 7{
            
            return UIImage(named: "common_icon_membership_level\(rank)")
            
        }else{
            
            return UIImage(named:"common_icon_membership_expired")
        }
    }
    
    ///MARK: - 认证图标
    func getVerifiedImage(verified: Int) -> UIImage?{
        switch verified{
            
        case 0:
            
            return UIImage(named: "avatar_vip")
            
        case 2,3,5:
            
            return UIImage(named: "avatar_enterprise_vip")
            
        case 220:
            
            return UIImage(named: "avatar_grassroot")
            
        default:
            
            return nil
        }
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setUI(){
        
        self.backgroundColor = UIColor.whiteColor()
    
        addSubview(headImageView)
        
        addSubview(nameLabel)
        
        addSubview(rankImageView)
        
        addSubview(timeLable)
        
        addSubview(sourceLabel)
        
        addSubview(verifiedImageView)
        
        addSubview(contentLabel)
        
        addSubview(pictureView)
        
        //添加约束
        headImageView.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.equalTo(10)
            
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(headImageView)
            
            make.leading.equalTo(headImageView.snp_trailing).offset(10)
        }
        
        rankImageView.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(nameLabel.snp_trailing).offset(10)
            
            make.centerY.equalTo(nameLabel)
        }
        
        timeLable.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(nameLabel)
            
            make.bottom.equalTo(headImageView)
        }
       
        sourceLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(timeLable.snp_trailing).offset(10)
            
            make.bottom.equalTo(timeLable)
        }
        
        verifiedImageView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(headImageView.snp_trailing)
            
            make.centerY.equalTo(headImageView.snp_bottom)
        }
        
        contentLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(headImageView.snp_bottom).offset(10)
            
            make.leading.equalTo(headImageView)
            
            make.width.equalTo(SCREENW - 20)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(contentLabel.snp_bottom).offset(10)
            
            make.leading.equalTo(contentLabel)
        }
        
        //给原创微博设置约束
        self.snp_makeConstraints { (make) -> Void in
            
            self.originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(10).constraint
        }
        
    }
    
    // MARK: - 懒加载控件
    private lazy var headImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    private lazy var nameLabel: UILabel = UILabel(textColor: UIColor.darkGrayColor(), textFont: 14)
    
    private lazy var rankImageView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    
    private lazy var timeLable: UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    
    private lazy var sourceLabel: UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    
    private lazy var verifiedImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_vgirl"))
    
    private lazy var contentLabel: UILabel = {
        
        let label = UILabel(textColor: UIColor.blackColor(), textFont: 14)
        
        label.numberOfLines = 0
        
        return label
    }()
    //配图
    private lazy var pictureView: LXStatusPictureView = LXStatusPictureView()

}
